
#include "editsnippetframe.h"

#include <wx/filename.h>
#include <wx/fileconf.h>
#include <wx/xrc/xmlres.h>


#include "codesnippetswindow.h"
#include "snippetsconfig.h"
#include "GenericMessageBox.h"
#include "version.h"

#include "sdk.h"
#include "sdk_events.h"
#include "configmanager.h"
#include "cbstyledtextctrl.h"
#include <wx/wxscintilla.h>
#include "cbauibook.h"

#include "defsext.h"
#include "prefs.h"
#include "seditorcolourset.h"
#include "scbeditor.h"
#include "seditormanager.h"
#include "editproperties.h"


extern int idEditHighlightMode;

extern int idEditHighlightModeText;

BEGIN_EVENT_TABLE(EditSnippetFrame, wxFrame)

  EVT_ACTIVATE(EditSnippetFrame::OnFrameActivated)

  EVT_CLOSE(EditSnippetFrame::OnCloseFrameOrWindow)

  EVT_SET_FOCUS(EditSnippetFrame::OnFocusWindow)
  EVT_KILL_FOCUS(EditSnippetFrame::OnKillFocusWindow)
  EVT_LEAVE_WINDOW(EditSnippetFrame::OnLeaveWindow)


  EVT_MENU(wxID_OPEN,             EditSnippetFrame::OnFileOpen)
  EVT_MENU(wxID_SAVE,             EditSnippetFrame::OnFileSave)
  EVT_MENU(wxID_SAVEAS,           EditSnippetFrame::OnFileSaveAs)
  EVT_MENU(wxID_CLOSE,            EditSnippetFrame::OnMenuFileClose)


  EVT_MENU(myID_PROPERTIES,       EditSnippetFrame::OnProperties)


  EVT_MENU(wxID_PRINT,            EditSnippetFrame::OnFilePrint)
  EVT_MENU(wxID_EXIT,             EditSnippetFrame::OnExit)


  EVT_MENU(wxID_CLEAR,            EditSnippetFrame::OnEditEvent)
  EVT_MENU(wxID_CUT,              EditSnippetFrame::OnEditEvent)
  EVT_MENU(wxID_COPY,             EditSnippetFrame::OnEditEvent)
  EVT_MENU(wxID_PASTE,            EditSnippetFrame::OnEditEvent)
  EVT_MENU(myID_INDENTINC,        EditSnippetFrame::OnEditEvent)
  EVT_MENU(myID_INDENTRED,        EditSnippetFrame::OnEditEvent)
  EVT_MENU(wxID_SELECTALL,        EditSnippetFrame::OnEditEvent)
  EVT_MENU(wxID_REDO,             EditSnippetFrame::OnEditEvent)
  EVT_MENU(wxID_UNDO,             EditSnippetFrame::OnEditEvent)


  EVT_MENU(wxID_FIND,      EditSnippetFrame::OnEditEvent)
  EVT_UPDATE_UI(wxID_FIND,      EditSnippetFrame::OnEditEventUI)
  EVT_MENU(myID_FINDNEXT,  EditSnippetFrame::OnEditEvent)
  EVT_UPDATE_UI(myID_FINDNEXT,  EditSnippetFrame::OnEditEventUI)
  EVT_MENU(myID_FINDPREV,  EditSnippetFrame::OnEditEvent)
  EVT_UPDATE_UI(myID_FINDPREV,  EditSnippetFrame::OnEditEventUI)

  EVT_MENU(myID_REPLACE,   EditSnippetFrame::OnEditEvent)
  EVT_UPDATE_UI(myID_REPLACE,   EditSnippetFrame::OnEditEventUI)
  EVT_MENU(myID_REPLACENEXT, EditSnippetFrame::OnEditEvent)
  EVT_UPDATE_UI(myID_REPLACENEXT, EditSnippetFrame::OnEditEventUI)

  EVT_MENU(myID_BRACEMATCH, EditSnippetFrame::OnEditEvent)
  EVT_UPDATE_UI(myID_BRACEMATCH, EditSnippetFrame::OnEditEventUI)

  EVT_MENU(myID_GOTO,             EditSnippetFrame::OnEditEvent)
  EVT_UPDATE_UI(myID_GOTO,        EditSnippetFrame::OnEditEventUI)



  EVT_MENU(idEditHighlightMode,     EditSnippetFrame::OnEditHighlightMode)


  EVT_UPDATE_UI(idEditHighlightMode, EditSnippetFrame::OnEditEventUI)
  EVT_UPDATE_UI(idEditHighlightModeText, EditSnippetFrame::OnEditEventUI)

  EVT_MENU(myID_DISPLAYEOL,       EditSnippetFrame::OnEditEvent)
  EVT_UPDATE_UI(myID_DISPLAYEOL,   EditSnippetFrame::OnEditEventUI)
  EVT_MENU(myID_INDENTGUIDE,      EditSnippetFrame::OnEditEvent)
  EVT_MENU(myID_LONGLINEON,       EditSnippetFrame::OnEditEvent)
  EVT_MENU(myID_WHITESPACE,       EditSnippetFrame::OnEditEvent)
  EVT_MENU(myID_FOLDTOGGLE,       EditSnippetFrame::OnEditEvent)
  EVT_MENU(myID_OVERTYPE,         EditSnippetFrame::OnEditEvent)
  EVT_MENU(myID_READONLY,         EditSnippetFrame::OnEditEvent)
  EVT_MENU(myID_WRAPMODEON,       EditSnippetFrame::OnEditEvent)

  EVT_MENU(myID_CHANGELOWER,      EditSnippetFrame::OnEditEvent)
  EVT_MENU(myID_CHANGEUPPER,      EditSnippetFrame::OnEditEvent)
  EVT_MENU(myID_CONVERTCR,        EditSnippetFrame::OnEditEvent)
  EVT_MENU(myID_CONVERTCRLF,      EditSnippetFrame::OnEditEvent)
  EVT_MENU(myID_CONVERTLF,        EditSnippetFrame::OnEditEvent)
  EVT_MENU(myID_CHARSETANSI,      EditSnippetFrame::OnEditEvent)
  EVT_MENU(myID_CHARSETMAC,       EditSnippetFrame::OnEditEvent)

  EVT_MENU(wxID_ABOUT,            EditSnippetFrame::OnAbout)

  EVT_EDITOR_SAVE(EditSnippetFrame::On_cbEditorSaveEvent)

END_EVENT_TABLE()

class EditFrameDropTextTarget : public wxTextDropTarget {


  public:
    EditFrameDropTextTarget(EditSnippetFrame* window) : m_Window(window) {}
    ~EditFrameDropTextTarget() {}
    bool OnDropText(wxCoord x, wxCoord y, const wxString& data);
  private:
    EditSnippetFrame* m_Window;
};

bool EditFrameDropTextTarget::OnDropText(wxCoord, wxCoord, const wxString& data) {
  #ifdef LOGGING
  LOGIT(_T("Dragged Data[%s]"), data.GetData());
  #endif
  m_Window->m_pScbEditor->GetControl()->AddText(data);
  return true;
}

class EditFrameDropFileTarget : public wxFileDropTarget {


  public:
    EditFrameDropFileTarget(EditSnippetFrame* window) : m_Window(window) {}
    ~EditFrameDropFileTarget() {}
    bool OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& filenames);
  private:
    EditSnippetFrame* m_Window;
};

bool EditFrameDropFileTarget::OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& arrayData) {
  if(arrayData.GetCount())
    m_Window->OpenDroppedFiles(arrayData);
  return true;
}


EditSnippetFrame::EditSnippetFrame(const wxTreeItemId  TreeItemId, int* pRetcode) {
  long windowStyle = wxDEFAULT_FRAME_STYLE;
  if(GetConfig()->GetEditorsStayOnTop())
    windowStyle = windowStyle | wxFRAME_FLOAT_ON_PARENT;
  Create(GetConfig()->GetSnippetsWindow(), wxID_ANY, _T("Edit snippet"),
         wxDefaultPosition, wxDefaultSize, windowStyle);
  InitEditSnippetFrame(TreeItemId, pRetcode);
  m_bEditorSaveEvent = 0;
}

void EditSnippetFrame::InitEditSnippetFrame(const wxTreeItemId  TreeItemId, int* pRetcode) {
  m_bOnActivateBusy = 0;
  m_ActiveEventId = 0;
  m_OncloseWindowEntries = 0;
  m_TmpFileName = wxEmptyString;
  m_pEditorManager = new SEditorManager(this);
  m_SnippetItemId = TreeItemId;
  m_EditSnippetText = GetConfig()->GetSnippetsTreeCtrl()->GetSnippet(TreeItemId);
  m_EditFileName = m_EditSnippetText.BeforeFirst('\r');
  m_EditFileName = m_EditFileName.BeforeFirst('\n');
  static const wxString delim(_T("$%["));
  if(m_EditFileName.find_first_of(delim) != wxString::npos)
    Manager::Get()->GetMacrosManager()->ReplaceMacros(m_EditFileName);
  if((m_EditFileName.Length() < 129) && (::wxFileExists(m_EditFileName)))
    ;
  else
    m_EditFileName = wxEmptyString;
  m_EditSnippetLabel = GetConfig()->GetSnippetsTreeCtrl()->GetSnippetLabel(TreeItemId);
  *pRetcode = 0;
  m_nReturnCode = wxID_CANCEL;
  m_pScbEditor = NULL;
  SetTitle(m_EditSnippetLabel);
  SetIcon(GetConfig()->GetSnipImages()->GetSnipListIcon(TREE_IMAGE_ALL_SNIPPETS));
  m_SysWinBkgdColour = wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW);
  SetBackgroundColour(m_SysWinBkgdColour);
  m_menuBar = new wxMenuBar;
  CreateMenu();
  if(not m_EditFileName.IsEmpty())
    m_pScbEditor = GetEditorManager()->Open(m_EditFileName);
  else {
    m_TmpFileName = wxFileName::GetTempDir();
    m_TmpFileName << _T("/") << m_EditSnippetLabel << _T(".txt");
    m_pScbEditor = GetEditorManager()->New(m_TmpFileName);
    m_pScbEditor->GetControl()->SetText(m_EditSnippetText);
    m_pScbEditor->SetModified(false);
    m_pScbEditor->GetControl()->EmptyUndoBuffer();
  }
  wxFileConfig cfgFile(wxEmptyString,
                       wxEmptyString,
                       GetConfig()->SettingsSnippetsCfgPath,
                       wxEmptyString,
                       wxCONFIG_USE_LOCAL_FILE);
  cfgFile.Read(wxT("EditDlgXpos"),       &GetConfig()->nEditDlgXpos, 20);
  cfgFile.Read(wxT("EditDlgYpos"),       &GetConfig()->nEditDlgYpos, 20);
  cfgFile.Read(wxT("EditDlgWidth"),      &GetConfig()->nEditDlgWidth, 500) ;
  cfgFile.Read(wxT("EditDlgHeight"),     &GetConfig()->nEditDlgHeight, 400) ;
  cfgFile.Read(wxT("EditDlgMaximized"),  &GetConfig()->bEditDlgMaximized, false);
  #if defined(LOGGING)
  LOGIT(_T("EditDlgPosition IN X[%d]Y[%d]Width[%d]Height[%d]"),
        GetConfig()->nEditDlgXpos, GetConfig()->nEditDlgYpos,
        GetConfig()->nEditDlgWidth, GetConfig()->nEditDlgHeight);
  #endif
  SetSize(GetConfig()->nEditDlgXpos, GetConfig()->nEditDlgYpos, GetConfig()->nEditDlgWidth, GetConfig()->nEditDlgHeight);
  m_pScbEditor->Connect(wxEVT_LEAVE_WINDOW,
                        (wxObjectEventFunction)(wxEventFunction)
                        (wxMouseEventFunction)&EditSnippetFrame::OnLeaveWindow,
                        NULL, this);
  m_pScbEditor->Connect(wxEVT_SET_FOCUS,
                        (wxObjectEventFunction)(wxEventFunction)
                        (wxFocusEventFunction)&EditSnippetFrame::OnFocusWindow,
                        NULL, this);
  m_pScbEditor->Connect(wxEVT_KILL_FOCUS,
                        (wxObjectEventFunction)(wxEventFunction)
                        (wxFocusEventFunction)&EditSnippetFrame::OnKillFocusWindow,
                        NULL, this);
  Connect(wxEVT_COMMAND_AUINOTEBOOK_PAGE_CLOSE,
          (wxObjectEventFunction)(wxEventFunction)
          (wxAuiNotebookEventFunction)&EditSnippetFrame::OnPageClose,
          NULL, this);
  Connect(cbEVT_EDITOR_SAVE,
          (wxObjectEventFunction)(wxEventFunction)
          (CodeBlocksEventFunction)&EditSnippetFrame::OncbEditorSave,
          NULL, this);
  SetDropTarget(new EditFrameDropFileTarget(this));
  m_pScbEditor->SetFocus();
}

EditSnippetFrame::~EditSnippetFrame() {
  if(m_pEditorManager) {
    if(m_pEditorManager) {
      ScbEditor* ed;
      int knt = m_pEditorManager->GetEditorsCount();
      for(int i = knt; i > 0; --i) {
        ed = (ScbEditor*)m_pEditorManager->GetEditor(i - 1);
        if(ed)
          ed->Close();
      }
    }
    RemoveEventHandler(m_pEditorManager);
    delete m_pEditorManager;
  }
  if(not m_TmpFileName.IsEmpty()) {
    ::wxRemoveFile(m_TmpFileName);
    m_TmpFileName = wxEmptyString;
  }
}

void EditSnippetFrame::SaveSnippetFramePosn() {
  wxString CfgFilenameStr = GetConfig()->SettingsSnippetsCfgPath;
  wxFileConfig cfgFile(wxEmptyString,
                       wxEmptyString,
                       CfgFilenameStr,
                       wxEmptyString,
                       wxCONFIG_USE_LOCAL_FILE);
  int x, y, w, h;
  GetPosition(&x, &y);
  GetSize(&w, &h);
  cfgFile.Write(wxT("EditDlgXpos"),  x);
  cfgFile.Write(wxT("EditDlgYpos"),  y);
  cfgFile.Write(wxT("EditDlgWidth"),  w);
  cfgFile.Write(wxT("EditDlgHeight"), h);
  #if defined(LOGGING)
  LOGIT(_T("EditDlgPositin OUT X[%d]Y[%d]Width[%d]Height[%d]"), x, y, w, h);
  #endif
  cfgFile.Write(wxT("EditDlgMaximized"),  false);
  cfgFile.Flush();
}

wxString EditSnippetFrame::GetName() {
  return m_EditSnippetLabel;
}


wxString EditSnippetFrame::GetText() {
  return m_EditSnippetText;
}





void EditSnippetFrame::OnHelp(wxCommandEvent&) {
}


void EditSnippetFrame::OnFocusWindow(wxFocusEvent &event) {
  #if defined(LOGGING)
  LOGIT(_T("EditSnippetFrame::OnFocusWindow"));
  #endif
  if(GetConfig()->IsExternalWindow())
  { event.Skip(); return; }
  event.Skip();
}

void EditSnippetFrame::OnKillFocusWindow(wxFocusEvent &event) {
  #if defined(LOGGING)
  LOGIT(_T("EditSnippetFrame::OnKillFocusWindow"));
  #endif
  event.Skip();
}

void EditSnippetFrame::OnLeaveWindow(wxMouseEvent &event) {
  #if defined(LOGGING)
  #endif
  event.Skip();
}

void EditSnippetFrame::OnAbout(wxCommandEvent &WXUNUSED(event)) {
}

void EditSnippetFrame::OnExit(wxCommandEvent &WXUNUSED(event)) {
  GetEditorManager()->CloseAll();
  Close(true);
}


void EditSnippetFrame::OnFileOpen(wxCommandEvent &WXUNUSED(event)) {
  if(! GetEditorManager())
    return;
  wxString fname;
  wxFileDialog dlg(this, _T("Open file"), _T(""), _T(""), _T("Any file (*)|*"),
                   wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_CHANGE_DIR);
  if(dlg.ShowModal() != wxID_OK)
    return;
  fname = dlg.GetPath();
  GetEditorManager()->Open(fname);
}

void EditSnippetFrame::On_cbEditorSaveEvent(CodeBlocksEvent& event) {
  ++m_bEditorSaveEvent;
  if(m_bEditorSaveEvent > 1)
    return;
  wxCommandEvent evt(wxEVT_COMMAND_MENU_SELECTED, wxID_SAVE);
  OnFileSave(evt);
  m_bEditorSaveEvent = 0;
  event.Skip();
}

void EditSnippetFrame::OnFileSave(wxCommandEvent& WXUNUSED(event)) {
  if(not GetEditorManager())
    return;
  if(not m_EditFileName.IsEmpty())
    GetEditorManager()->SaveActive();
  else if(GetEditorManager()->GetActiveEditor() == m_pScbEditor) {
    m_EditSnippetText = m_pScbEditor->GetControl()->GetText();
    m_nReturnCode = wxID_OK;
    m_pScbEditor->SetModified(false);
    GetConfig()->GetSnippetsTreeCtrl()->SaveEditorsXmlData(this);
  }
}

void EditSnippetFrame::OnFileSaveAs(wxCommandEvent &WXUNUSED(event)) {
  if(not GetEditorManager())
    return;
  m_ActiveEventId = wxID_SAVEAS;
  GetEditorManager()->SaveActiveAs();
  m_ActiveEventId = 0;
}

void EditSnippetFrame::OncbEditorSave(CodeBlocksEvent& event) {
  event.Skip();
  if(m_ActiveEventId == wxID_SAVEAS)
    return;
  SEditorBase* eb = GetEditorManager()->GetActiveEditor();
  if(m_pScbEditor && (eb == m_pScbEditor))
    OnFileCheckModified();
}

void EditSnippetFrame::OnPageClose(wxAuiNotebookEvent event) {
  #if defined(LOGGING)
  LOGIT(_T("EditSnippetFrame::OnPageClose"));
  #endif
  event.Skip();
  cbAuiNotebook* pnb = (cbAuiNotebook*)event.GetEventObject();
  SEditorBase* eb = static_cast<SEditorBase*>(pnb->GetPage(event.GetSelection()));
  if(m_pScbEditor && (eb == m_pScbEditor)) {
    OnFileCheckModified();
    m_pScbEditor = 0;
  }
  if(1 >= GetEditorManager()->GetEditorsCount()) {
    wxCloseEvent closeEvent(wxEVT_CLOSE_WINDOW, this->GetId());
    closeEvent.SetEventObject(this);
    AddPendingEvent(closeEvent);
  }
}

void EditSnippetFrame::OnCloseFrameOrWindow(wxCloseEvent &event) {
  #if defined(LOGGING)
  LOGIT(_T("EditSnippetFrame::OnCloseFrameOrWindow"));
  #endif
  if(m_OncloseWindowEntries++)
    return;
  SaveSnippetFramePosn();
  GetConfig()->GetSnippetsTreeCtrl()->SaveDataAndCloseEditorFrame(this);
  m_OncloseWindowEntries = ((m_OncloseWindowEntries < 1) ? 0 : m_OncloseWindowEntries - 1);
}



void EditSnippetFrame::OnMenuFileClose(wxCommandEvent &) {
  if(GetEditorManager()->GetEditorsCount()) {
    SEditorBase* eb = GetEditorManager()->GetActiveEditor();
    GetEditorManager()->Close(eb);
    if(eb == m_pScbEditor)
      m_pScbEditor = 0;
  }
  if(0 >= GetEditorManager()->GetEditorsCount()) {
    wxCloseEvent closeEvent(wxEVT_CLOSE_WINDOW, this->GetId());
    closeEvent.SetEventObject(this);
    AddPendingEvent(closeEvent);
  }
}

void EditSnippetFrame::OnFileCheckModified() {
  if(not m_pScbEditor)
    return;
  SEditorBase* eb = GetEditorManager()->GetActiveEditor();
  if(not eb)
    return;
  if(eb not_eq m_pScbEditor)
    return;
  if(m_pScbEditor->GetModified()) {
    if(not m_EditFileName.IsEmpty()) {
    } else {
      m_EditSnippetText = m_pScbEditor->GetControl()->GetText();
      m_nReturnCode = wxID_OK;
      m_pScbEditor->SetModified(false);
      m_pScbEditor->GetControl()->SetSavePoint();
    }
  }
}

void EditSnippetFrame::OnProperties(wxCommandEvent&) {
  ScbEditor* ed = GetEditorManager()->GetBuiltinActiveEditor();
  EditProperties* pDlg = new EditProperties(this, ed);
  delete pDlg;
}







void EditSnippetFrame::OnEditEvent(wxCommandEvent &event) {
  SEditorBase* eb = GetEditorManager()->GetActiveEditor();
  ScbEditor* ed = GetEditorManager()->GetBuiltinActiveEditor();
  if((not ed) || (not eb))
    return;
  cbStyledTextCtrl* stcCtrl = ed->GetControl();
  if(not stcCtrl)
    return;
  int id = event.GetId();
  switch(id) {
    case wxID_CLEAR:
      ed->GetControl()->LineCut();
      break;
    case wxID_CUT:
      ed->Cut();
      break;
    case wxID_COPY:
      ed->Copy();
      break;
    case wxID_PASTE:
      ed->Paste();
      break;
    case myID_INDENTINC:
      ed->DoIndent();
      break;
    case myID_INDENTRED:
      ed->DoUnIndent();
      break;
    case wxID_SELECTALL:
      ed->GetControl()->SelectAll();
      break;
    case myID_OVERTYPE:
      ed->GetControl()->SetOvertype(!ed->GetControl()->GetOvertype());
      break;
    case wxID_REDO:
      ed->Redo();
      break;
    case wxID_UNDO:
      ed->Undo();
      break;
    case myID_DISPLAYEOL:
      stcCtrl->SetViewEOL(!stcCtrl->GetViewEOL());
      break;
    case myID_INDENTGUIDE:
      stcCtrl->SetIndentationGuides(! stcCtrl->GetIndentationGuides());
      break;
    case myID_LONGLINEON:
      stcCtrl->SetEdgeMode(stcCtrl->GetEdgeMode() == 0 ? wxSCI_EDGE_LINE : wxSCI_EDGE_NONE);
      break;
    case myID_WHITESPACE:
      stcCtrl->SetViewWhiteSpace(stcCtrl->GetViewWhiteSpace() == 0 ?
                                 wxSCI_WS_VISIBLEALWAYS : wxSCI_WS_INVISIBLE);
      break;
    case wxID_FIND:
      eb->SearchFind();
      break;
    case myID_FINDNEXT:
    case myID_FINDPREV:
      eb->SearchFindNext(id == myID_FINDNEXT);
      break;
    case myID_REPLACE:
    case myID_REPLACENEXT:
      eb->OnSearchReplace();
      break;
    case myID_BRACEMATCH:
      ed->GotoMatchingBrace();
      break;
    case myID_GOTO:
      eb->SearchGotoLine();
      break;
    case myID_READONLY:
      stcCtrl->SetReadOnly(! stcCtrl->GetReadOnly());
      break;
    case myID_CHARSETANSI:
    case myID_CHARSETMAC: {
      int Nr;
      int charset = stcCtrl->GetCodePage();
      switch(event.GetId()) {
        case myID_CHARSETANSI:
        {charset = wxSCI_CHARSET_ANSI; break;}
        case myID_CHARSETMAC:
        {charset = wxSCI_CHARSET_ANSI; break;}
      }
      for(Nr = 0; Nr < wxSCI_STYLE_LASTPREDEFINED; Nr++)
        stcCtrl->StyleSetCharacterSet(Nr, charset);
      stcCtrl->SetCodePage(charset);
      break;
    }
    case myID_CHANGEUPPER:
    case myID_CHANGELOWER: {
      switch(event.GetId()) {
        case myID_CHANGELOWER: {
          stcCtrl->CmdKeyExecute(wxSCI_CMD_LOWERCASE);
          break;
        }
        case myID_CHANGEUPPER: {
          stcCtrl->CmdKeyExecute(wxSCI_CMD_UPPERCASE);
          break;
        }
      }
      break;
    }
    case myID_CONVERTCR:
    case myID_CONVERTCRLF:
    case myID_CONVERTLF:
      OnConvertEOL(event);
      break;
    case myID_WRAPMODEON:
      stcCtrl->SetWrapMode(stcCtrl->GetWrapMode() == 0 ? wxSCI_WRAP_WORD : wxSCI_WRAP_NONE);
      break;
    default:
      break;
  }
}

void EditSnippetFrame::OnConvertEOL(wxCommandEvent &event) {
  SEditorBase* eb = GetEditorManager()->GetActiveEditor();
  ScbEditor* ed = GetEditorManager()->GetBuiltinActiveEditor();
  if((not ed) || (not eb))
    return;
  cbStyledTextCtrl* stcCtrl = ed->GetControl();
  if(not stcCtrl)
    return;
  int id = event.GetId();
  wxUnusedVar(id);
  int eolMode = stcCtrl->GetEOLMode();
  switch(event.GetId()) {
    case myID_CONVERTCR:
    { eolMode = wxSCI_EOL_CR; break;}
    case myID_CONVERTCRLF:
    { eolMode = wxSCI_EOL_CRLF; break;}
    case myID_CONVERTLF:
    { eolMode = wxSCI_EOL_LF; break;}
  }
  stcCtrl->ConvertEOLs(eolMode);
  stcCtrl->SetEOLMode(eolMode);
}

void EditSnippetFrame::OnEditEventUI(wxUpdateUIEvent &event) {
  int id = event.GetId();
  wxUnusedVar(id);
  ScbEditor* ed = GetEditorManager()->GetBuiltinActiveEditor();
  if(not ed) {
    event.Skip();
    return;
  }
  {
    wxMenu* hl = 0;
    m_menuBar->FindItem(idEditHighlightModeText, &hl);
    if(hl)
      m_menuBar->Check(hl->FindItem(ed->GetColourSet()->GetLanguageName(ed->GetLanguage())), true);
  }
  if(GetEditorManager()->GetEditorsCount() > 0) {
    if(GetEditorManager()->GetActiveEditor())
      event.Enable(true);
  } else
    event.Enable(false);
}


void EditSnippetFrame::CreateMenu() {
  wxMenu *menuFile = new wxMenu;
  menuFile->Append(wxID_OPEN, _("&Open ..\tCtrl+O"));
  menuFile->Append(wxID_SAVE, _("&Save\tCtrl+S"));
  menuFile->Append(wxID_SAVEAS, _("Save &as ..\tCtrl+Shift+S"));
  menuFile->Append(wxID_CLOSE, _("&Close\tCtrl+W"));
  menuFile->AppendSeparator();
  menuFile->Append(myID_PROPERTIES, _("Proper&ties ..\tCtrl+I"));
  menuFile->Append(wxID_PRINT, _("&Print ..\tCtrl+P"));
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXIT, _("&Quit\tCtrl+Q"));
  wxMenu *menuEdit = new wxMenu;
  menuEdit->Append(wxID_UNDO, _("&Undo\tCtrl+Z"));
  menuEdit->Append(wxID_REDO, _("&Redo\tCtrl+Shift+Z"));
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_CUT, _("Cu&t\tCtrl+X"));
  menuEdit->Append(wxID_COPY, _("&Copy\tCtrl+C"));
  menuEdit->Append(wxID_PASTE, _("&Paste\tCtrl+V"));
  menuEdit->Append(wxID_CLEAR, _("&LineDelete\tCtrl+L"));
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_FIND, _("&Find\tCtrl+F"));
  menuEdit->Enable(wxID_FIND, false);
  menuEdit->Append(myID_FINDNEXT, _("Find &next\tF3"));
  menuEdit->Enable(myID_FINDNEXT, false);
  menuEdit->Append(myID_FINDPREV,       _("Find pre&vious\tShift+F3"));
  menuEdit->Enable(myID_FINDPREV, false);
  menuEdit->Append(myID_REPLACE, _("&Replace\tCtrl+R"));
  menuEdit->Enable(myID_REPLACE, false);
  menuEdit->Append(myID_REPLACENEXT, _("Replace &again\tShift+F4"));
  menuEdit->Enable(myID_REPLACENEXT, false);
  menuEdit->AppendSeparator();
  menuEdit->Append(myID_BRACEMATCH, _("&Match brace\tCtrl+M"));
  menuEdit->Append(myID_GOTO, _("&Goto\tCtrl+G"));
  menuEdit->AppendSeparator();
  menuEdit->Append(myID_INDENTINC, _("&Indent increase\tTab"));
  menuEdit->Append(myID_INDENTRED, _("I&ndent reduce\tBksp"));
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_SELECTALL, _("&Select all\tCtrl+A"));
  wxMenu *menuCharset = new wxMenu;
  menuCharset->Append(myID_CHARSETANSI, _("&ANSI (Windows)"));
  menuCharset->Append(myID_CHARSETMAC, _("&MAC (Macintosh)"));
  wxMenu *menuView = new wxMenu;
  wxMenu* menuHilight = new wxMenu;
  CreateMenuViewLanguage(menuHilight);
  menuView->Append(idEditHighlightMode, _("&Hilight language .."), menuHilight);
  menuView->AppendSeparator();
  menuView->AppendCheckItem(myID_OVERTYPE, _("&Overwrite mode\tIns"));
  menuView->Check(myID_OVERTYPE, g_CommonPrefs.overTypeInitial);
  menuView->AppendCheckItem(myID_WRAPMODEON, _("&Wrap mode\tCtrl+U"));
  menuView->Check(myID_WRAPMODEON, g_CommonPrefs.wrapModeInitial);
  menuView->AppendSeparator();
  menuView->AppendCheckItem(myID_DISPLAYEOL, _("Show line &endings"));
  menuView->Check(myID_DISPLAYEOL, g_CommonPrefs.displayEOLEnable);
  menuView->AppendCheckItem(myID_INDENTGUIDE, _("Show &indent guides"));
  menuView->Check(myID_INDENTGUIDE, g_CommonPrefs.indentGuideEnable);
  menuView->AppendCheckItem(myID_LONGLINEON, _("Show &long line marker"));
  menuView->Check(myID_LONGLINEON, g_CommonPrefs.longLineOnEnable);
  menuView->AppendCheckItem(myID_WHITESPACE, _("Show white&space"));
  menuView->Check(myID_WHITESPACE, g_CommonPrefs.whiteSpaceEnable);
  menuView->AppendSeparator();
  menuView->Append(myID_USECHARSET, _("Use &code page of .."), menuCharset);
  wxMenu *menuChangeCase = new wxMenu;
  menuChangeCase->Append(myID_CHANGEUPPER, _("&Upper case"));
  menuChangeCase->Append(myID_CHANGELOWER, _("&Lower case"));
  wxMenu *menuConvertEOL = new wxMenu;
  menuConvertEOL->Append(myID_CONVERTCR, _("CR (&Linux)"));
  menuConvertEOL->Append(myID_CONVERTCRLF, _("CR+LF (&Windows)"));
  menuConvertEOL->Append(myID_CONVERTLF, _("LF (&Macintosh)"));
  wxMenu *menuExtra = new wxMenu;
  menuExtra->AppendCheckItem(myID_READONLY, _("&Readonly mode"));
  menuExtra->Check(myID_READONLY, g_CommonPrefs.readOnlyInitial);
  menuExtra->AppendSeparator();
  menuExtra->Append(myID_CHANGECASE, _("Change &case to .."), menuChangeCase);
  menuExtra->AppendSeparator();
  menuExtra->Append(myID_CONVERTEOL, _("Convert line &endings to .."), menuConvertEOL);
  m_menuBar->Append(menuFile, _("&File"));
  m_menuBar->Append(menuEdit, _("&Edit"));
  m_menuBar->Append(menuView, _("&View"));
  m_menuBar->Append(menuExtra, _("E&xtra"));
  SetMenuBar(m_menuBar);
}

void EditSnippetFrame::CreateMenuViewLanguage(wxMenu* menuHilight) {
  wxMenu* hl = menuHilight;
  int id = idEditHighlightModeText;
  hl->AppendRadioItem(id, _T("Plain text"), wxString::Format(_("Switch highlighting mode for current document to \"%s\""), _T("Plain text")));
  Connect(id, -1, wxEVT_COMMAND_MENU_SELECTED,
          (wxObjectEventFunction)(wxEventFunction)(wxCommandEventFunction)
          &EditSnippetFrame::OnEditHighlightMode);
  {
    if(hl) {
      SEditorColourSet* theme = GetEditorManager()->GetColourSet();
      if(theme) {
        wxArrayString langs = theme->GetAllHighlightLanguages();
        for(size_t i = 0; i < langs.GetCount(); ++i) {
          if(i > 0 && !(i % 20))
            hl->Break();
          int id = wxNewId();
          hl->AppendRadioItem(id, langs[i],
                              wxString::Format(_("Switch highlighting mode for current document to \"%s\""), langs[i].c_str()));
          Connect(id, -1, wxEVT_COMMAND_MENU_SELECTED,
                  (wxObjectEventFunction)(wxEventFunction)(wxCommandEventFunction)
                  &EditSnippetFrame::OnEditHighlightMode);
        }
      }
    }
  }
}

void EditSnippetFrame::FileOpen(wxString fname) {
  wxFileName w(fname);
  w.Normalize();
  fname = w.GetFullPath();
  GetEditorManager()->Open(fname);
}


wxRect EditSnippetFrame::DeterminePrintSize() {
  wxSize scr = wxGetDisplaySize();
  wxRect rect = GetRect();
  rect.x += 16;
  rect.y += 16;
  rect.width = wxMin(rect.width, (scr.x - rect.x));
  rect.height = wxMin(rect.height, (scr.x - rect.y));
  return rect;
}

void EditSnippetFrame::OnFilePrint(wxCommandEvent&) {
  GetEditorManager()->FilePrint(this);
}

void EditSnippetFrame::OnEditHighlightMode(wxCommandEvent& event) {
  ScbEditor* ed = GetEditorManager()->GetBuiltinActiveEditor();
  if(ed) {
    SEditorColourSet* theme = GetEditorManager()->GetColourSet();
    if(theme) {
      HighlightLanguage lang = theme->GetHighlightLanguage(_T(""));
      if(event.GetId() != idEditHighlightModeText) {
        wxMenu* hl = 0;
        GetMenuBar()->FindItem(idEditHighlightModeText, &hl);
        if(hl) {
          wxMenuItem* item = hl->FindItem(event.GetId());
          if(item)
          #if wxCHECK_VERSION(3, 0, 0)
            lang = theme->GetHighlightLanguage(item->GetItemLabelText());
          #else
            lang = theme->GetHighlightLanguage(item->GetLabel());
          #endif
        }
      }
      ed->SetLanguage(lang);
    }
  }
}

void EditSnippetFrame::OnFrameActivated(wxActivateEvent& event) {
  if(m_bOnActivateBusy) {
    event.Skip();
    return;
  }
  ++m_bOnActivateBusy;
  if(event.GetActive())
    do {
      if(not GetConfig()->GetSnippetsWindow())
        break;
      if(not GetConfig()->GetSnippetsTreeCtrl())
        break;
      #if defined(LOGGING)
      LOGIT(_T("EditSnippetFrame::OnAppActivate"));
      #endif
      if((GetConfig()->GetEditorManager(this))
          && (Manager::Get()->GetConfigManager(_T("app"))->ReadBool(_T("/environment/check_modified_files"), true))
        ) {
        wxCommandEvent evt(wxEVT_COMMAND_MENU_SELECTED, idSEditorManagerCheckFiles);
        wxPostEvent(GetConfig()->GetEditorManager(this), evt);
      }
    } while(0);
  m_bOnActivateBusy = 0;
  return;
}

void EditSnippetFrame::OpenDroppedFiles(const wxArrayString& arrayData) {
  for(int i = 0; i < (int)arrayData.GetCount(); ++i) {
    #ifdef LOGGING
    LOGIT(_T("Dragged File[%s]"), arrayData.Item(i).c_str());
    #endif
    wxString filename = arrayData.Item(i);
    if(wxFileExists(filename)) {
      ScbEditor* sed = GetEditorManager()->Open(filename);
      if(sed) {
      }
    }
  }
}

